package com.boot.core.util

import java.lang.reflect.Field
import java.util.*

object BeanUtil {

    fun <T> listField2Set(field: String, targetList: List<T>):  MutableSet<Any> {
        val set = HashSet<Any>(0)
        for (t in targetList) {
            t?.let {
                val fieldValue = getFieldValue(t, field)
                if (fieldValue != null) {
                    set.add(fieldValue.toString())
                }
            }

        }
        return set
    }

    private fun getFieldValue(obj: Any, fieldName: String): Any? {
        var result: Any? = null
        val field = BeanUtil.getField(obj, fieldName)
        if (field != null) {
            field.isAccessible = true
            try {
                result = field.get(obj)
            } catch (e: IllegalArgumentException) {
                e.printStackTrace()
            } catch (e: IllegalAccessException) {
                e.printStackTrace()
            }
        }
        return result
    }

    private fun getField(obj: Any, fieldName: String): Field? {
        var field: Field? = null
        var clazz: Class<*> = obj.javaClass
        while (clazz != Any::class.java) {
            try {
                field = clazz.getDeclaredField(fieldName)
                break
            } catch (e: NoSuchFieldException) {
            }
            clazz = clazz.superclass
        }
        return field
    }

}